﻿using System.Web;
using System.Xml.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marbles.Core.Web.Cart
{ 
    [Serializable()]
    public class Cart : ICart
    {
        [XmlIgnore()]
        public string Owner { get { return this._owner; } }

        [XmlIgnore()]
        public string ID { get { return this._id; } }

        [XmlIgnore()]
        public decimal Total
        {
            get { return CalculateTotal(); }
        }

        [XmlIgnore()]
        public int Count
        {
            get { return this._Items.Count; }
        }

        [XmlIgnore()]
        public ICartItem[] Items
        {
            get { return this._Items.ToArray(); }
        }

        [XmlAttribute("CartId")]
        protected string CartId { get { return this._id; } set { this._id = value; } }

        [XmlAttribute("Items")]
        protected ICartItem[] CartItems
        {
            get { return this._Items.ToArray(); }
            set
            {
                this._Items.Clear();
                this._Items = new List<ICartItem>(value);
            }
        }

        [XmlAttribute("Owner")]
        protected string CartOwner
        {
            get { return this._owner; }
            set
            {
                this._owner = value;
            }
        }


        private List<ICartItem> _Items = null;
        private string _id = string.Empty;
        private string _owner = string.Empty;

        public Cart()
        {
            this._id = Guid.NewGuid().ToString();
            this._owner = HttpContext.Current.User.Identity.Name;
        }

        public void Add(IProduct Product, int Quantity)
        {
            foreach (ICartItem item in this._Items)
            {
                if (item.Product == Product)
                {
                    item.Quantity = Quantity;
                    return;
                }
            }

            this._Items.Add(new CartItem(Product, Quantity));
        }

        public void Update(IProduct Product, int Quantity)
        {
            foreach (ICartItem item in this._Items)
            {
                if (item.Product == Product)
                {
                    item.Quantity = Quantity;
                    return;
                }
            }

            this._Items.Add(new CartItem(Product, Quantity));
        }

        private decimal CalculateTotal()
        {
            decimal total = 0;

            foreach (ICartItem item in this._Items)
            {
                total += item.Total;
            }

            return total;
        }

    }
}
